package role

import (
	"reflect"
	codecs "sanguo/codec/cs"
	"sanguo/node/common/aoi"
	"sanguo/node/node_map"
	"sanguo/node/node_map/scene"
	cs_message "sanguo/protocol/cs/message"
	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/move"

	"github.com/golang/protobuf/proto"
)

type Move struct {
}

func (this *Move) OnCall(replyer *move.MoveReplyer, arg *ss_rpc.MoveReq) {

	scene_ := scene.GetSceneByType(scene.SceneType(arg.GetMapType()))

	if nil == scene_ {
		replyer.Reply(&ss_rpc.MoveResp{
			Ok: proto.Int32(0),
		})
		return
	}

	scene_.PostTask(func() {

		sceneO := scene_.GetObjByID(arg.GetUserID())
		if nil == sceneO {
			replyer.Reply(&ss_rpc.MoveResp{
				Ok: proto.Int32(0),
			})
			return
		}

		scenePos := arg.GetPos()
		aoiPos := aoi.Position{
			X: scenePos.GetX(),
			Y: scenePos.GetY(),
		}

		if scene_.Move(sceneO, aoiPos) {

			sceneO.(*Role).ScenePos.X = scenePos.GetX()
			sceneO.(*Role).ScenePos.Y = scenePos.GetY()
			sceneO.(*Role).ScenePos.Z = scenePos.GetZ()
			sceneO.(*Role).ScenePos.Angle = arg.GetAngle()

			replyer.Reply(&ss_rpc.MoveResp{
				Ok:    proto.Int32(1),
				Pos:   scenePos,
				Angle: proto.Int32(arg.GetAngle()),
			})
		} else {
			replyer.Reply(&ss_rpc.MoveResp{
				Ok: proto.Int32(0),
			})
		}
	})
}

func (this *Role) NotifyPosUpdate() {

	msg := &cs_message.UpdatePosToC{}
	msg.Objs = []*cs_message.UpdateObj{
		&cs_message.UpdateObj{
			RoleID: proto.Uint64(this.ID),
			Pos: &cs_message.Position{
				X: proto.Int32(this.ScenePos.X),
				Y: proto.Int32(this.ScenePos.Y),
				Z: proto.Int32(this.ScenePos.Z),
			},
			Angle: proto.Int32(this.ScenePos.Angle),
		},
	}

	//node_map.Infoln(msg)
	msgType := reflect.TypeOf(msg).String()
	bytes, err := encoder.EnCode(codecs.NewMessage(0, msg))

	if err != nil {
		node_map.Infoln("OnAoiUpdate err", err)
		return
	}

	this.SendViewObjToClient(msgType, bytes.Bytes())

}

func init() {
	move.Register(&Move{})
}
